package ru.megazlo.basemvc.controllers;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import ru.megazlo.basemvc.controllers.base.Action;
import ru.megazlo.basemvc.controllers.base.BaseController;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;

@ControllerAdvice
@Controller
public class ErrorController extends BaseController {

	private final String BODY = "body";

	@RequestMapping("/error/404")
	@Action(elem = BODY)
	public Object page404(HttpServletResponse response) {
		return getResult(response);
	}

	@ExceptionHandler(value = Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@Action(elem = BODY)
	public Object page500(Throwable ex, HttpServletResponse response) {
		return getResult("errorMessage", "Message: " + ex.getMessage() + "<br/>Stack trace: " + stackTraceToString(ex), response);
	}

	public String stackTraceToString(Throwable e) {
		StringWriter sw = new StringWriter();
		e.printStackTrace(new PrintWriter(sw));
		return sw.toString();
	}

	@RequestMapping("/error/denied")
	@Action(elem = BODY)
	public Object denied(HttpServletResponse response) {
		return getResult(response);
	}

	@RequestMapping("/error/other")
	//@Common(title = "Неизвестная ошибка", selector = CONTENT, view = "error/other")
	public Object other(Exception ex) {
		return "error/other";
	}
}
